<?php

namespace App\Http\Resources;

use Illuminate\Http\Request;

class DepartmentResource extends BaseResource
{
    /**
     * Transform the resource into an array.
     *
     * @return array<string, mixed>
     */
    public function toArray(Request $request): array
    {
        return [
            'id' => $this->id,
            'parent_id' => $this->parent_id,
            'name' => $this->name,
            'code' => $this->code,
            'leader' => $this->leader,
            'phone' => $this->phone,
            'email' => $this->email,
            'status' => $this->status,
            'sort' => $this->sort,
            'remark' => $this->remark,
            'parent' => $this->whenLoaded('parent', function () {
                return [
                    'id' => $this->parent->id,
                    'name' => $this->parent->name,
                ];
            }),
            'children' => $this->when($this->relationLoaded('children'), function () {
                $children = $this->children;
                if ($children instanceof \Illuminate\Database\Eloquent\Collection && $children->isNotEmpty()) {
                    // 递归转换为资源集合
                    return DepartmentResource::collection($children)->resolve(request());
                }
                return [];
            }),
            'created_at' => $this->formatDateTime($this->created_at),
            'updated_at' => $this->formatDateTime($this->updated_at),
        ];
    }
}

